package demo;
class Counter{
    private static int ret=0;
    private Object locker=new Object();
    //每个非静态方法存在一个天然的对象，即this
    public void add(){
        //private Object locker=new Object();  =>locker不能定义在函数内部
        //因为如果定义在内部，那么每次进入函数就会创建新的Object对象，他们不是用一个锁对象
        synchronized(locker) {
            ret++;
        }
    }

    public static void sum(){
        synchronized (Counter.class){
            ret++;
        }
    }
    public int getRet(){
        return ret;
    }
}
public class Demo1 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter=new Counter();
        Thread t1=new Thread(()->{
            for(int i=0;i<50000;i++){
                counter.add();
            }
        });
        Thread t2=new Thread(()->{
            for(int i=0;i<50000;i++){
                counter.add();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(counter.getRet());
    }
}
